﻿using System;
using System.Collections.Generic;
using System.Linq;
using CatClient.Fusing;
using CatClient.Util;

namespace CatClient.Configuration
{
    public class ClientConfig
    {
        private readonly Random _random = new Random();

        private static readonly object _lock = new object();

        private List<Server> _server = new List<Server>();

        public ClientConfig(Domain domain = null, params Server[] serverList)
        {
            this.Domain = domain ?? new Domain(null, false, 100000, 1);
            if (serverList != null && serverList.Length > 0)
                this.Servers.AddRange(serverList);
        }

        public Domain Domain { get; set; }

        public List<Server> Servers
        {
            get
            {
                return this._server;
            }
            set
            {
                lock (_lock)
                {
                    this._server = value;
                }
            }
        }

        public void Initialize()
        {
            lock (_lock)
            {
                this.LoadServerConfig();
            }
        }

        public void RandomServer()
        {
            if (this._server == null || this._server.Count < 2)
                return;

            for (int i = 0; i < this._server.Count * 3; i++)
            {
                int num = i % this._server.Count;
                int numNxt = this._random.Next(this._server.Count);
                if (numNxt != num)
                {
                    Server value = this._server[num];
                    this._server[num] = this._server[numNxt];
                    this._server[numNxt] = value;
                }
            }
        }

        public void LoadServerConfig()
        {
            string serverConfigUrl = this.GetServerConfigUrl();
            if (string.IsNullOrWhiteSpace(serverConfigUrl))
            {
                LogInfoWriter.GetInstance("Cat", 0, LogInfoWriter.LogLayout.Default).Warn("LoadServerConfig: none server!");
                Cat.GetFuseManager().Increment(FuseType.Connection);
                return;
            }
            LogInfoWriter.GetInstance("Cat", 0, LogInfoWriter.LogLayout.Default).Info(string.Format("Get servers : {0}", serverConfigUrl));
            string[] array = serverConfigUrl.Split(new char[]
            {
                ';'

            }, StringSplitOptions.RemoveEmptyEntries);
            List<Server> list = new List<Server>();
            foreach (string text in array)
            {
                try
                {
                    string[] array3 = text.Split(new char[]
                    {
                        ':'
                    });
                    string ip = array3[0].Trim();
                    string s = array3[1].Trim();
                    list.Add(new Server(ip, int.Parse(s), 8080, true));
                }
                catch
                {
                }
            }
            if (list.Count > 0)
            {
                this.Servers = list;
                return;
            }
            Cat.GetFuseManager().Increment(FuseType.Connection);
        }

        private string GetServerConfigUrl()
        {
            var servers = this._server.Where(x => x.Enabled);
            foreach (Server server in servers)
            {
                try
                {
                    string request = CatHttpRequest.GetRequest(string.Format("http://{0}:{1}/cat/s/router?domain={2}", server.Ip, server.HttpPort, this.Domain.Id ?? "cat"));
                    if (!string.IsNullOrEmpty(request))
                    {
                        return request;
                    }
                }
                catch{}
            }
            return string.Empty;
        }
    }
}
